package com.ai.networking.netty.decoder;

import com.ai.common.constant.AlgorithmConstant;
import com.ai.entity.network.L1ToIdentifySysMessage;
import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 解码
 * @Author jiaok
 * @Date 2023-06-20 11:44
 */
@Slf4j
public class L1ToSysMessageDecoder extends ByteToMessageDecoder {


    //会发送信号的ip
    private static final ArrayList<String>  signalIpList= new ArrayList<>(Arrays.asList("140.24.30.3","140.24.30.4","140.24.30.5","127.0.0.1","192.168.8.153","192.168.8.33"));

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext,
                          ByteBuf byteBuf,
                          List<Object> out) throws Exception {

        InetSocketAddress ipSocket = (InetSocketAddress) channelHandlerContext.channel().remoteAddress();
        String clientIp = ipSocket.getAddress().getHostAddress();
        Integer port = ipSocket.getPort();
        if (signalIpList.contains(clientIp)){
            //处理信号

            //电文头  电文长度
            Integer telLen = byteBuf.readInt();
            //电文号
            Integer telId = byteBuf.readInt();

            //判断是否为心跳电文
            if (telId.equals(AlgorithmConstant.PLC_TO_SYSTEM_HEARTBEAT)
                    || telId.equals(AlgorithmConstant.FURNACE_TO_SYSTEM_HEARTBEAT_30_4)
                    || telId.equals(AlgorithmConstant.FURNACE_TO_SYSTEM_HEARTBEAT_30_5)){
                log.info("    -------------------  开始解析L1发送的心跳信号 开始解析  -------------------    ");

                Integer counter = byteBuf.readInt();
                byte[] heartBeatSpareBytes = new byte[24];
                byteBuf.readBytes(heartBeatSpareBytes);
                String heartBeatSpare = new String(heartBeatSpareBytes);

                log.info("    -------------------  开始解析L1发送的心跳信号 解析完毕  -------------------    ");
                L1ToIdentifySysMessage l1ToIdentifyHeartBeatSysMessage = new L1ToIdentifySysMessage();
                l1ToIdentifyHeartBeatSysMessage.setTelId(telId);
                l1ToIdentifyHeartBeatSysMessage.setTelLen(telLen);
                l1ToIdentifyHeartBeatSysMessage.setCounter(counter);
                l1ToIdentifyHeartBeatSysMessage.setSpare(heartBeatSpare);
                l1ToIdentifyHeartBeatSysMessage.setHeartBeat(true);
                l1ToIdentifyHeartBeatSysMessage.setClientIp(clientIp);//客户端ip
                l1ToIdentifyHeartBeatSysMessage.setSourcePort(port);//客户端端口
                log.info("=========================== 接收到心跳报文：{}  ===========================", JSONObject.toJSONString(l1ToIdentifyHeartBeatSysMessage));
                out.add(l1ToIdentifyHeartBeatSysMessage);//将解析过之后的数据放置于管道中
                return;
            }

            log.info("    -------------------  开始解析L1发送的操作信号  开始解析  -------------------    ");


            //  版批号----- 心跳电文没有
            byte[] planNoBytes = new byte[12];
            byteBuf.readBytes(planNoBytes);
            String planNo = new String(planNoBytes);

            String state="";
            String doorNum="";
            //不同的电文信号，解析为不同的字段
            if (telId.equals(AlgorithmConstant.A3_TRANSFER_MACHINE_AUTOMATIC_CONFIRMATION) ||
                    telId.equals(AlgorithmConstant.TRACK_STACKING_STEEL)){
                //A3移载机自动确认 开始/关闭指令 或者  输入辊道叠钢 开始/关闭指令
                state = String.valueOf(byteBuf.readInt());
            } else  {
                //加热炉电文类型
                doorNum = String.valueOf(byteBuf.readInt());
            }

            //冗余字段
            byte[] spareBytes = new byte[24];
            byteBuf.readBytes(spareBytes);
            String spare = new String(spareBytes);

            /**
             * 粘包半包处理，  后期完善
             */
//        if (telId.equals(AlgorithmConstant.PLC_TO_SYSTEM_HEARTBEAT) ||
//                telId.equals(AlgorithmConstant.FURNACE_TO_SYSTEM_HEARTBEAT_30_4) ||
//                    telId.equals(AlgorithmConstant.FURNACE_TO_SYSTEM_HEARTBEAT_30_5)){
//            //则说明为心跳电文 判断长度是否满足
//
//        }
//
//        if (byteBuf.readableBytes()< 42){
//            return; // 电文长度不足，不予解析
//        }

            log.info("    -------------------  开始解析L1发送的操作信号  解析完毕  -------------------    ");
            L1ToIdentifySysMessage l1ToIdentifySysMessage = new L1ToIdentifySysMessage();
            l1ToIdentifySysMessage.setTelLen(telLen);
            l1ToIdentifySysMessage.setTelId(telId);
            l1ToIdentifySysMessage.setPlanNo(planNo);
            l1ToIdentifySysMessage.setHeartBeat(false);
            if (!StringUtils.isBlank(state)){
                l1ToIdentifySysMessage.setState(Integer.valueOf(state));
            } else if (!StringUtils.isBlank(spare)) {
                l1ToIdentifySysMessage.setDoorNum(Integer.valueOf(doorNum));
            }
            l1ToIdentifySysMessage.setSpare(spare);
            l1ToIdentifySysMessage.setClientIp(clientIp);//客户端ip
            l1ToIdentifySysMessage.setSourcePort(port);//客户端端口
            log.info("=========================== 接收到操作报文：{}  ===========================", JSONObject.toJSONString(l1ToIdentifySysMessage));
//        byteBuf.markReaderIndex();//数据解析结束，标记当前位置
            out.add(l1ToIdentifySysMessage);//将解析过之后的数据放置于管道中
        }



    }
}
